<template>
  <div class="edu-page-warp information-page">
    <div class="edu-page-title">{{ $t('information.releaseMgt') }}</div>
    <el-card shadow="never">
      <div slot="header">
        <span>{{ $t('information.contentMaintenance') }}</span>
      </div>
      <el-form :model="informationForm" ref="informationForm" label-width="90px" :rules="rules">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item :label="$t('information.label')" prop="label">
              <el-select v-model="informationForm.label" :placeholder="$t('common.pla.pleaseSelect')">
                <el-option
                  v-for="item in options.labelList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('information.inValidateTime')" prop="bulletinDuration">
              <el-date-picker
                v-model="informationForm.bulletinDuration"
                type="date"
                format="yyyy/MM/dd"
                value-format="timestamp">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('information.whetherToTop')" prop="topStatus">
              <el-checkbox v-model="informationForm.topStatus"></el-checkbox>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item :label="$t('information.topInvalidateTime')" prop="invalidTopTime">
              <el-date-picker
                v-model="informationForm.invalidTopTime"
                type="date"
                format="yyyy/MM/dd"
                value-format="timestamp">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('information.type')" prop="type">
              <el-select v-model="informationForm.type" :placeholder="$t('common.pla.pleaseSelect')">
                <el-option
                  v-for="item in options.typeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('information.institutionalScope')" prop="schoolRange">
              <el-select v-model="informationForm.schoolRange" :placeholder="$t('common.pla.pleaseSelect')">
                <el-option
                  v-for="item in options.institutionalScopeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item :label="$t('information.teacherAndStudentRange')" prop="tsRange">
              <el-select v-model="informationForm.tsRange" :placeholder="$t('common.pla.pleaseSelect')">
                <el-option
                  v-for="item in options.teacherAndStudentRangeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item :label="$t('information.title')" prop="title">
              <el-input v-model="informationForm.title"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item :label="$t('information.content')" prop="content">
              <tinymce ref="editor" :height="150" v-model="informationForm.content"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card class="upload-card" shadow="never">
      <div slot="header">
        <span>{{ $t('information.contentMaintenance') }}</span>
      </div>
      <div class="upload-info">
        <el-upload
          :headers="{'X-Token': $store.state.session.sessionid}"
          :data="{bucketname: 'face', folderpath: 'file'}"
          :on-remove="handleFileRemove"
          :on-success="handleUploadSuccess"
          :file-list="informationFileList"
          class="upload-demo"
          action="/api/commonservice/obsfile/uploadfile"
          multiple
        >
          <el-button class="operate-add" type="primary" @click="addInformation">上传附件</el-button>
        </el-upload>
        
      </div>
    </el-card>
    <div class="footer-wrapper">
      <div class="btn-list">
        <el-button type="primary" @click="handleAddCommonPublicMsg">{{$t('information.save')}}</el-button>
        <!-- <el-button type="primary" @click="handleCheckCommonPublicMsg">{{$t('information.submitApplication')}}</el-button> -->
      </div>
    </div>
    <el-dialog
      title="提示"
      :visible.sync="saveDialogVisible"
      :show-close="false"
      width="35%">
      <span>{{contentTip}}</span>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="gotoMyInformation">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import Tinymce from 'common/src/components/Tinymce';
  import { queryDic } from 'common/src/api/dictionary';
  import { addCommonPublicMsg, updateCommonPublicMsg, checkCommonPublicMsg, findCommonPublicMsgById } from 'common/src/api/public/information'
  import Bus from 'common/src/utils/bus';

  export default {
    name: '',
    components: {
      'tinymce': Tinymce
    },
    data: function() {
      return {
        informationForm: {
          status: '1',
          commonAttachmentList: []
        },
        options: {
          labelList: [],
          typeList: [],
          institutionalScopeList: [],
          teacherAndStudentRangeList: []
        },
        contentTip: '',
        saveDialogVisible: false,
        informationFileList: [],
        rules: {
          label: [{ 
            required: true, 
            message: this.$t("information.msg.label"), 
            trigger: "change"
          }],
          bulletinDuration: [{ 
            required: true, 
            message: this.$t("information.msg.inValidateTime"), 
            trigger: "change"
          }],
          type: [{ 
            required: true, 
            message: this.$t("information.msg.type"), 
            trigger: "change"
          }],
          schoolRange: [{ 
            required: true, 
            message: this.$t("information.msg.institutionalScope"), 
            trigger: "change"
          }],
          tsRange: [{ 
            required: true, 
            message: this.$t("information.msg.teacherAndStudentRange"), 
            trigger: "change"
          }],
          title: [{ 
            required: true, 
            message: this.$t("information.msg.title"), 
            trigger: "blur"
          }],
          content: [{ 
            required: true, 
            message: this.$t("information.msg.content"), 
            trigger: "blur"
          }]
        }
      }
    },
    created() {
      const informationId = this.$route.params.id;
      this.informationId = informationId || '';
      this.getOptions();
    },
    mounted() {
    },
    methods: {
      handleFileRemove(file, fileList) {
        this.informationFileList = fileList;
        this.informationForm.commonAttachmentList = this.setInformationAttachList(fileList);
      },
      handleUploadSuccess(res, file, fileList) {
        this.informationFileList = fileList
        this.informationForm.commonAttachmentList = this.setInformationAttachList(fileList);
      },
      setInformationAttachList(fileList) {
        let attachList = [];
        fileList.forEach(item => {
          if (item.response && item.response.data) {
            const uploadedObj = item.response.data[item.name];
            if (uploadedObj) {
              const attachObj = {};
              attachObj.fileName = uploadedObj.fileName;
              attachObj.fileLacation = uploadedObj.objectkey;
              attachList.push(attachObj);
            }
          }
        });
        return attachList;
      },
      handleAddCommonPublicMsg() {
        this.$refs.informationForm.validate(valid => {
          if (!valid) { return; }
          const topStatusCheckbox = this.informationForm.topStatus;
          this.informationForm.topStatus = topStatusCheckbox ? '1': '0';
          if (this.informationId) {
            updateCommonPublicMsg(this.informationForm).then(res => {
              if (res.code == 200) {
                this.handleSavedSuccess();
              }
            });
          } else {
            addCommonPublicMsg(this.informationForm).then(res => {
              if (res.code == 200) {
                this.handleSavedSuccess();
              }
            });
          }
        });
      },
      handleSavedSuccess() {
        // this.resetInformationForm();
        this.contentTip = '信息公告已保存，可前往我的信息发布中编辑或提交审核';
        this.saveDialogVisible = true;
      },
      gotoMyInformation: function() {
        this.saveDialogVisible = false;
        // 回到列表页面
        this.$router.push('/myInformation/');
      },
      resetInformationForm() {
        this.informationForm = {
          status: '1'
        }
      },
      handleFindCommonPublicMsgById(id) {
        findCommonPublicMsgById(id).then(res => {
          this.informationForm = res.data;
          this.informationForm.topStatus = this.informationForm.topStatus == '1';
          console.log(res.data, '----------------');
          this.informationFileList = this.getInformationAttachList(res.data.commonAttachmentList);
        });
      },
      getInformationAttachList(fileList) {
        let attachList = [];
        fileList.forEach(item => {
          const attachObj = {};
          attachObj.name = item.fileName;
          attachObj.url = item.fileLacation;
          attachList.push(attachObj);
        });
        return attachList;
      },
      getOptions() {
        const data = {
          lang: this.$store.getters.language || 'cn',
          type: 'allChild',
          keys: ['K_LABEL', 'K_XXLX', 'K_XYFW', 'K_SSFW'],
        }
        queryDic(data).then((res) => {
          if (res.code === 200) {
            this.fillSelect(res.data);
            // 查询当前信息
            if (this.informationId) {
              this.handleFindCommonPublicMsgById(this.informationId);
            }
          }
        });
      },
      fillSelect(data) {
        let { K_LABEL, K_XXLX, K_XYFW, K_SSFW } = data;
        this._fill('labelList', K_LABEL);
        this._fill('typeList', K_XXLX)
        this._fill('institutionalScopeList', K_XYFW)
        this._fill('teacherAndStudentRangeList', K_SSFW)
      },
      _fill(type, data) {
        for (const key in data) {
          this.options[type].push({
            value: key,
            label: data[key],
          })
        }
      },
    }
    
  }
</script>

<style lang="scss" scoped>
  .information-page {
    .el-date-editor.el-input {
      width: 100%;
    }
    .el-select {
      width: 100%;
    }
  }
  .upload-card {
    margin-top: 10px;
  }
  .footer-wrapper {
    width: 100%;
    background: #fff;
    padding: 15px 0; 
    .btn-list {
      text-align: right;
    }
  }
  
</style>
